package com.nstc.sftpExchange.service;

import com.alibaba.fastjson.JSONObject;
import com.nstc.sftpExchange.common.RestResponse;
import com.nstc.sftpExchange.config.httpClient.HttpClient;
import com.nstc.sftpExchange.config.httpClient.HttpClientResult;
import com.nstc.sftpExchange.entity.scope.UploadScope;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Service
public class RequestSftpExchangeService {

    @Value("${nstc.business.sftp-exchange-request.url}")
    private String requestUrl;

    @Resource
    private HttpClient httpClient;

    public RestResponse<String> requestSftpExchange(UploadScope uploadScope) {
        log.info("请求参数：{}", uploadScope == null ? "无参数" : JSONObject.toJSONString(uploadScope));
        if (StringUtils.isBlank(requestUrl)) {
            return RestResponse.failure("系统配置错误，转发异常");
        }

        try {
            Map<String, String> headers = new HashMap<>();
            headers.put("Content-Type", "application/json");
            headers.put("Accept", "application/json");

            HttpClientResult httpClientResult = httpClient.doPost(requestUrl, headers, uploadScope);
            RestResponse restResponse = JSONObject.parseObject(httpClientResult.getContent(), RestResponse.class);
            if (restResponse.getCode() != 200){
                log.error("转发异常，转发响应：{}", JSONObject.toJSONString(restResponse));
            }
            return restResponse;
        } catch (Exception e) {
            log.error("转发异常", e);
            return RestResponse.failure("系统配置错误，转发失败");
        }
    }
}
